import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { WeaTools, WeaLocaleProvider, WeaRightMenu, WeaNewScroll, WeaDialog, WeaSelect, WeaHelpfulTip, WeaTextarea, WeaError } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
import { WeaTableNew, WeaSwitch } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import { Row, Col, message, Modal, Button } from 'antd';
import HighSeasConditionTarget from './HighSeasConditionTarget';
import ConditionEdit from './ConditionEdit';

@observer
export default class HighSeasConditionDialog extends React.Component {
  constructor(props) {
    super(props);
  }


  componentWillMount() {
    this.changeContentHeight();
  }

  render() {
    const { store } = this.props;
    const { conditionInfo, visible, mask, fieldRecord, relationtypeOptions, relation, ruleSql, root, isShowSql, contentHeight, checkButtonDisabled } = store;
    const { conditiontype, fieldOptions, conditionsql2, mainTablename } = conditionInfo;

    let targetFieldid = '';
    if (fieldRecord && fieldRecord.key && fieldRecord.key > 0) {
      targetFieldid = `${fieldRecord.key}`;
    }

    const conditiontypeOptions = [{
      key: '1',
      showname: getLabel(2086, '普通') + getLabel(33234, '类型'),
    }, {
      key: '2',
      showname: 'sql',
    }];
    const { key } = fieldRecord;
    let sql = getLabel(84304, '暂无');
    if (ruleSql != '') {
      sql = ruleSql;
    }

    const buttons = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0wwg2k@save`} type="primary" loading={store.dialogLoading} onClick={() => this.onRightMenuClick('save')} >{getLabel(826, '确定') }</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@h5pnpf@clear`} onClick={() => this.onRightMenuClick('clean')}>{getLabel(15504, '清空')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0hdu3k@check`} disabled={checkButtonDisabled} onClick={() => this.onRightMenuClick('checkSQL')}>{getLabel(82691, '检测条件')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@f1b3vc@back`} onClick={() => this.onRightMenuClick('toback')}>{getLabel(1290, '返回')}</Button>];

    return (
      <WeaDialog
        ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@9pz5qw`}
        buttons={buttons}
        title={getLabel(384164, '条件设置')}
        iconBgcolor="#96358a"
        icon="icon-coms-crm"
        visible={visible}
        onCancel={() => this.onRightMenuClick('toback')}
        style={{ width: 1100, height: 600 }}
        mask={mask}
      >
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@fkjwgf`} datas={this.getRightMenu(checkButtonDisabled)} onClick={this.onRightMenuClick.bind(this)}>
          {/* <WeaNewScroll > */}
          <div className="wev-crm-highseas-condition-warp">
            <div className="wev-crm-highseas-condition-top" >
              <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@g8ynsx`}>
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@jmg3p1`} span={6} style={{ width: 210 }}>
                  <div className="wev-crm-highseas-field-label">
                    {getLabel(23243, '条件类型')}
                  </div>
                  <div className="wev-crm-highseas-field">
                    <WeaSelect
                      ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@rvggbg`}
                      key={conditiontype}
                      value={conditiontype}
                      options={toJS(conditiontypeOptions)}
                      style={{ width: 120 }}
                      viewAttr={3}
                      onChange={v => this.changeFieldValue('conditiontype', v)}
                    />
                  </div>
                </Col>
                {conditiontype && conditiontype == '1' &&
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@m17eiv`} span={6} style={{ width: 245 }}>
                  <div className="wev-crm-highseas-field-label">
                    {getLabel(15620, '目标字段')}
                  </div>
                  <div className="wev-crm-highseas-field">
                    <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@a1e264`} style={{ width: '100%' }} tipPosition="bottom" ref="targetFieldid" error={getLabel(18214, '请选择') + getLabel(15620, '目标字段')}>
                      <WeaSelect
                        ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@dowyo0`}
                        filterOption={(inputValue, option) => selectFilterOption(inputValue, option)}
                        options={toJS(fieldOptions)}
                        style={{ width: 160 }}
                        value={targetFieldid}
                        viewAttr={3}
                        onChange={v => this.changeFieldValue('targetFieldid', v)}
                      />
                    </WeaError>
                  </div>
                </Col>
                }

                {conditiontype && conditiontype == '1' &&
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@zm5c4i`} span={6} style={{ width: 140 }}>
                  {key && key > 0 &&
                  <WeaSelect
                    ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@vbzdy8`}
                    key={relationtypeOptions.length}
                    value={relation}
                    options={toJS(relationtypeOptions)}
                    style={{ width: 120 }}
                    viewAttr={2}
                    onChange={v => this.changeFieldValue('relation', v)}
                  />
                  }
                </Col>
                }


                {conditiontype && conditiontype == '1' &&
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@4dbzq5`} span={6} style={{ width: 200 }}>
                  {key && key > 0 &&
                    // <WeaError style={{width:'100%'}} tipPosition='bottom' ref="targetFieldvalue" error={getLabel(15642,"目标字段不能为空")}>
                  <HighSeasConditionTarget ecId={`${this && this.props && this.props.ecId || ''}_HighSeasConditionTarget@n9gg79`} {...this.props} ctype="top" />
                    // </WeaError>
                  }
                </Col>
                }
              </Row>
            </div>
            {conditiontype && conditiontype == '1' &&
            <div>
              <div className="wev-crm-highseas-condition-button">
                <div className="btns">
                  <div onClick={() => this.addParam()} title={getLabel(611, '添加')} className="btn-icon add" />
                  <div onClick={() => { this.delParam(); }} title={getLabel(23777, '删除')} className="btn-icon del" />
                  <div onClick={() => this.addbracket(0)} title={getLabel(24542, '添加或条件')} className="btn-icon joinor" />
                  <div onClick={() => this.addbracket(1)} title={getLabel(24541, '添加与条件')} className="btn-icon joinand" />
                  <div onClick={() => { this.splitCondition(); }} title={getLabel(33576, '拆分条件')} className="btn-icon spit" />
                </div>
              </div>
              <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@im5ckq`} ref="contentScroll" height={contentHeight} >
                <div className="wev-crm-highseas-condition-content">
                  <div id="ruleContent" >
                    <div id="expressionBlock">
                      {this.getRelationItems(root, true)}
                    </div>
                  </div>
                </div>
              </WeaNewScroll>
              <div id="ruleSQL" className={isShowSql ? '' : 'hide'}>
                <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@8sb5on`} height={60} >
                  {sql}
                </WeaNewScroll>
              </div>
              <div id="ruledescBtn" onClick={() => this.changeShowSql()} className={`operbtn ${isShowSql ? 'operbtn_down' : 'operbtn_up'}`} />
            </div>
            }
            {conditiontype && conditiontype == '2' &&
            <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@p9snvq`} key={sql.length} height={520} >
              <div className="wev-crm-highseas-condition-sql">
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@rvy2yn`}>
                  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@mk5v90`} span={2}>
                    <div className="sqlLabel">sql</div>
                  </Col>
                  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@w7aa5k`} span={20}>
                    <div className="sqlArea">
                      <WeaError
                        ecId={`${this && this.props && this.props.ecId || ''}_WeaError@l5v7uz`}
                        tipPosition="bottom"
                        error={`${'sql' + '"'}${getLabel(21423, '未填写')}`}
                        style={{ width: '100%' }}
                        ref={(ref) => { store.refObj.sql_ = ref; }}
                      >
                        <WeaTextarea
                          ecId={`${this && this.props && this.props.ecId || ''}_WeaTextarea@p2btlv`}
                          minRows={10}
                          value={conditionsql2}
                          viewAttr={2}
                          onChange={v => this.changeFieldValue('conditionsql2', v)}
                        />
                      </WeaError>
                    </div>
                    <div className="sqlDesc">
                      <WeaHelpfulTip
                        ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@fpozlm`}
                        width={300}
                        title={getLabel(128096, "格式为：table1.a='1' and table2.b='2'，其中table1,table2为数据库表名 a,b为字段名")}
                      />&nbsp;
                      {getLabel(128096, "格式为：table1.a='1' and table2.b='2'，其中table1,table2为数据库表名 a,b为字段名")}
                      <br />
                      {mainTablename && mainTablename.length > 2 && <div>{getLabel(21778, '主表') + getLabel(127392, '：') + mainTablename}</div> }
                      {/* {getLabel(21778,"主表")+getLabel(127392,"：")+mainTablename}
                                                {
                                                    detailTables&&detailTables.length>0&&
                                                    detailTables.map((item)=>{
                                                        return <div>{item.name+getLabel(127392,"：")+item.detailtable}</div>
                                                    })
                                                } */}
                    </div>
                  </Col>
                </Row>

              </div>
            </WeaNewScroll>
            }
          </div>
          {/* </WeaNewScroll> */}
        </WeaRightMenu>
      </WeaDialog >
    );
  }

    // 右键菜单
    getRightMenu=(checkButtonDisabled) => {
      const btns = new Array();
      btns.push({ key: 'save', icon: <i className="icon-coms-Preservation" />, content: getLabel(826, '确定', 'label') });
      btns.push({ key: 'clean', icon: <i className="icon-coms-go-back" />, content: getLabel(15504, '清空') });
      btns.push({ key: 'checkSQL', icon: <i className="icon-coms-help" />, content: getLabel(82691, '检测条件'), disabled: checkButtonDisabled });
      btns.push({ key: 'toback', icon: <i className="icon-coms-Revoke" />, content: getLabel(1290, '返回') });
      return btns;
    }

    // 右键菜单事件绑定
    onRightMenuClick=(key) => {
      const { store } = this.props;
      const { fieldRecord, targetValue, conditionInfo } = store;

      if (key == 'save') {
        // if(conditionInfo.conditiontype&&conditionInfo.conditiontype=='1'){
        //     if(!(fieldRecord&&fieldRecord.key&&fieldRecord.key>0)){
        //         this.refs.targetFieldid.showError();
        //         return ;
        //     }
        //     if(targetValue==""){
        //         this.refs.targetFieldvalue.showError();
        //         return ;
        //     }
        // }

        store.onSave();
      } else if (key == 'clean') {
        store.deleteCondition();
      } else if (key == 'checkSQL') {
        // if(conditionInfo.conditiontype&&conditionInfo.conditiontype=='1'){
        //     if(!(fieldRecord&&fieldRecord.key&&fieldRecord.key>0)){
        //         this.refs.targetFieldid.showError();
        //         return ;
        //     }
        //     if(targetValue==""){
        //         this.refs.targetFieldvalue.showError();
        //         return ;
        //     }
        // }
        store.checkSQL();
      } else if (key == 'toback') {
        store.onCancel();
      }
    }

    toShowErrorSql=(sql, vdatasource) => {
      let ds = '';
      if (vdatasource && vdatasource != '') {
        if (vdatasource == '$ECOLOGY_SYS_LOCAL_POOLNAME') {
          vdatasource = 'local';
        }
        ds = <div>{getLabel(18076, '数据源')}：{vdatasource}</div>;
      }
      Modal.error({
        title: getLabel(127353, '错误') + getLabel(15364, '条件'),
        content: (
          <div className="wea-error-sql">
            <div>{getLabel(385170, '条件检测未通过，具体SQL如下：')}</div>
            {sql}
            {ds}
          </div>
        ),
        onOk() {},
        width: 800,
      });
    }

    changeFieldValue=(key, value) => {
      const { store } = this.props;
      const { conditionInfo } = store;
      const { fieldOptions } = conditionInfo;
      if (key == 'targetFieldid') {
        store.targetValue = '';
        store.targetValueSpan = '';
        if (value != '') {
          for (let i = 0; i < fieldOptions.length; i++) {
            if (fieldOptions[i].key == value) {
              store.fieldRecord = fieldOptions[i];
              if (store.fieldRecord.fieldhtmltype == '4') { // checkbox
                store.targetValue = '0';
              }
              this.getRelationtypeOption();
              break;
            }
          }
        } else {
          store.fieldRecord = {};
        }
        store.relation = '4';
        store.isChange = true;
      } else if (key == 'conditiontype') {
        this.changeModified();
        conditionInfo.conditiontype = value;
      } else if (key == 'relation') {
        store.relation = value;
        store.isChange = true;
      } else if (key == 'conditionsql2') {
        conditionInfo.conditionsql2 = value;
        this.changeModified();
      }
    }

    getRelationtypeOption=() => {
      const { store } = this.props;
      const { fieldRecord } = store;
      const { relationtype, type } = fieldRecord;
      const arr = store.getRelationArr(relationtype, type);
      store.relationtypeOptions = arr;
    }

    getSelectedObj(key, array) {
      let obj;
      for (let i = 0; i < array.length; i++) {
        if (key == array[i].key) {
          obj = array[i];
          break;
        }
      }
      return obj;
    }

    getValue4Obj=() => {
      const { store } = this.props;
      const { fieldRecord, targetValue, targetValueSpan, relation, relationtypeOptions, conditionField } = store;
      const { fieldname, fieldid, fieldhtmltype, type, fielddbtype, relationtype, valueshowtype, showname, tablename } = fieldRecord;
      const fieldlabel = showname;
      const valetype = valueshowtype;
      const htmltype = fieldhtmltype; // 大类型
      const fieldtype = type;	// 小类型
      const dbtype = fielddbtype;// 数据库类型
      //
      let compareopion = relation;
      if (dbtype == 'text' || dbtype == 'clob' || (fieldtype == '162' || fieldtype == '257')) {
        compareopion = '100';
      }
      let compareopionlabel = '';
      let selectObj = this.getSelectedObj(relation, relationtypeOptions);
      if (selectObj) {
        compareopionlabel = selectObj.showname;
      }
      // value span 取值
      const fieldvalue = targetValue;
      let fieldtext = targetValue;
      if (valetype == 4) { // 浏览框
        fieldtext = targetValueSpan;
      } else if (valetype == 5) { // 下拉框
        const { selectOption } = conditionField;
        const arr = selectOption[`option_${fieldid}`];
        selectObj = this.getSelectedObj(targetValue, arr);
        if (selectObj) {
          fieldtext = selectObj.showname;
        }
      } else if (valetype == 6) { // check框
        fieldtext = targetValueSpan;
      }

      // 组装字符串 显示和后台所需
      const hiddenarea = {
        key: new Date().getTime(),
        fieldid,
        fieldname,
        fieldlabel,
        htmltype,
        fieldtype,
        fielddbtype,
        compareopion,
        compareopionlabel,
        fieldvalue,
        fieldtext,
        relationtype,
        valetype,
        tablename,
      };
      return hiddenarea;
    }

    // 获取表达式当前index
    getExpIndex =() => {
      const { store } = this.props;
      const { conditionInfo } = store;
      const { count } = conditionInfo;
      conditionInfo.count = count + 1;
      return conditionInfo.count;
    };

    // 拼接条件显示 方法
    showDisplaySpan=(areaJson) => {
      const { htmltype, fieldtype, fieldlabel } = areaJson;
      let text = `'${areaJson.fieldtext}'`;
      if (htmltype == '1') {
        if (fieldtype != '1') {
          text = areaJson.fieldtext;
        }
      }
      const displayspan = `${fieldlabel} ${areaJson.compareopionlabel} ${text}`;
      return displayspan;
    }

   getNode=(area, pid) => {
     const noded = {
       isParent: false,
       parentNode: pid,
       ...area,
     };
     return noded;
   }

    addParam=() => {
      const { store } = this.props;
      const { fieldRecord, targetValue, root, selectedItemKey, selectedItemParentNode } = store;
      if (!(fieldRecord && fieldRecord.key && fieldRecord.key > 0)) {
        this.refs.targetFieldid.showError();
        // message.error(getLabel(18214,"请选择")+getLabel(15620,"目标字段"));
        return;
      }
      // if(targetValue==""){
      //     this.refs.targetFieldvalue.showError();
      //     // message.error(getLabel(15642,"目标字段不能为空"));
      //     return ;
      // }

      const area = this.getValue4Obj();
      if (selectedItemKey.length > 0) {
        area.parentNode = selectedItemParentNode;
        this.addToTree(root, area);
      } else if (root && root.key && root.key > 0) {
        area.parentNode = root.key;
        const node = this.getNode(area, root.key);
        const { datas } = root;
        datas.push(node);
      } else {
        const k = new Date().getTime();
        const node = this.getNode(area, k);
        const obj = { key: k, relationship: '1', isParent: true, parentNode: '', datas: [node] };
        store.root = obj;
      }
      store.isChange = false;
      this.getRuleSql();
      this.changeModified();
      const contentScroll = this.refs.contentScroll;
      setTimeout(() => {
        contentScroll.scrollToLast();
      }, 100);
    }

    addToTree =(item, area, datasArray) => {
      const { store } = this.props;
      const { selectedItemParentNode } = store;
      const { isParent, key, datas } = item;
      let flag = false;
      if (isParent) { // 父节点
        if (selectedItemParentNode == key) {
          const node = this.getNode(area, key);
          datas.push(node);
          flag = true;
        } else {
          for (let i = 0; i < datas.length; i++) {
            if (this.addToTree(datas[i], area, datas)) {
              break;
            }
          }
        }
      }
      return flag;
    }

    changeModified = () => {
      const { store } = this.props;
      store.ismodified = '1';
    }

    switchSelected = (e, areaJson) => {
      clearTimeout(this.timer);
      const { store } = this.props;
      const { selectedItemKey, selectedItemParentNode } = store;
      const { parentNode } = areaJson;
      this.timer = window.setTimeout(() => {
        if (selectedItemKey.length > 0) {
          if (selectedItemParentNode != parentNode) {
            store.selectedItemKey = [];
          } else {
            const index = store.selectedItemKey.indexOf(areaJson.key);
            if (index > -1) { // 已经选中,则取消选中
              store.selectedItemKey.splice(index, 1);
              if (store.selectedItemKey.length == 0) {
                store.selectedItemParentNode = '';
              }
              return;
            }
          }
        }
        store.selectedItemKey.push(areaJson.key);
        store.selectedItemParentNode = areaJson.parentNode;
      }, 300);
    }

    switchSelectedDiv(e, areaJson) {
      if (e.target) { // 阻止事件冒泡
        const id = e.target.getAttribute('id');
        if (id && (id == `relationblock_${areaJson.key}` || id == `relationItem_${areaJson.key}`)) {
          this.switchSelected(e, areaJson);
        }
      }
    }

    delFromArray = (array, selectRowIds) => {
      for (let i = 0; i < selectRowIds.length; i++) {
        const key = selectRowIds[i];
        for (let j = 0; j < array.length; j++) {
          if (array[j].key == key) {
            array.splice(j, 1);
            break;
          }
        }
      }
      return array;
    }

    cancelBackFun=(areaJson) => {
      if (areaJson) {
        const { store } = this.props;
        this.delFromArray(store.editArr, [areaJson.key]);
      }
      this.getRuleSql();
      this.setState({
        time: new Date().getTime(),
      });
    }

    toEditItem = (areaJson) => {
      const { store } = this.props;
      clearTimeout(this.timer);
      areaJson.isEdit = 1;
      this.changeContentHeight();
      store.selectedItemKey = [];
      store.selectedItemParentNode = '';
      store.editArr.push(areaJson);
      this.setState({
        time: new Date().getTime(),
      });
    }
    switchRelationEditMode = (itemObj) => {
      const { relationship } = itemObj;
      if (relationship == '0') {
        itemObj.relationship = '1';
      } else {
        itemObj.relationship = '0';
      }
      this.getRuleSql();
    }


     // 返回表达式显示文字
     expressdescElement = (areaJson) => {
       const { store } = this.props;
       let { selectedItemKey } = store;
       let selectedCss = '';
       selectedItemKey = selectedItemKey.slice(0);
       if (selectedItemKey.indexOf(areaJson.key) > -1) {
         selectedCss = ' spanselected';
       }
       const displayspan = this.showDisplaySpan(areaJson);
       const { key } = areaJson;
       return (
         <span
           onClick={e => this.switchSelected(e, areaJson)}
           onDoubleClick={e => this.toEditItem(areaJson)}
           className={`displayspan${selectedCss}`}
           key={key}
         >
           {displayspan}
         </span>);
     };

    // 添加条件 (0:或/1：与)
    addbracket = (relationship) => {
      const { store } = this.props;
      const { selectedItemKey, selectedItemParentNode, root } = store;
      if (selectedItemKey.length < 2) {
        return;
      }
      const childsum = $(`#relationblock_${selectedItemParentNode}`).children('.relationItem').length;
      if (childsum == selectedItemKey.length) {
        message.error(getLabel(84546, '关系已存在'));
        return;
      }
      this.changeData(root, relationship);
      store.selectedItemKey = [];
      store.selectedItemParentNode = '';
      this.getRuleSql();
      this.changeModified();
    };

    changeData=(item, relationship) => {
      const { store } = this.props;
      const { selectedItemKey, selectedItemParentNode } = store;
      const { key, isParent, datas } = item;
      let flag = false;
      if (isParent) {
        if (key == selectedItemParentNode) {
          const newArray = new Array();
          const selectArr = new Array();
          let firstIndex = -1;// 第一次出现的位置
          const newKey = new Date().getTime();
          let oldParentNode = '';
          for (let i = 0; i < datas.length; i++) {
            let isSelected = false;// 是否被选中
            for (let j = 0; j < selectedItemKey.length; j++) {
              if (selectedItemKey[j] == datas[i].key) {
                isSelected = true;
                break;
              }
            }
            if (isSelected) {
              if (firstIndex == -1) {
                firstIndex = i;
                oldParentNode = datas[i].parentNode;
              }
              datas[i].parentNode = newKey;
              selectArr.push(datas[i]);
            } else {
              newArray.push(datas[i]);
            }
          }
          const newNode = { key: newKey, relationship, isParent: true, parentNode: oldParentNode, datas: selectArr };
          newArray.splice(firstIndex, 0, newNode);
          item.datas = newArray;

          flag = true;
        } else {
          for (let i = 0; i < datas.length; i++) {
            if (this.changeData(datas[i], relationship)) {
              break;
            }
          }
        }
      }
      return flag;
    }

    // 删除已有并选中的条件
    delParam=() => {
      const { store } = this.props;
      const { selectedItemKey, root } = store;
      if (selectedItemKey.length > 0) {
        const deleteData = this.deleteData;
        const getRuleSql = this.getRuleSql;
        Modal.confirm({
          title: getLabel(33475, '确认要删除选中记录吗？'),
          onOk() {
            deleteData(root);
            store.selectedItemKey = [];
            store.selectedItemParentNode = '';
            getRuleSql();
          },
          onCancel() {},
        });
        this.changeModified();
      }
    }

    deleteData=(item) => {
      const { store } = this.props;
      const { selectedItemKey, selectedItemParentNode, root } = store;
      const { key, isParent, datas, parentNode } = item;
      let flag = false;
      if (isParent) {
        if (key == selectedItemParentNode) {
          const remainArray = new Array();// 剩余的数据
          for (let i = 0; i < datas.length; i++) {
            let isSelected = false;// 是否被选中
            for (let j = 0; j < selectedItemKey.length; j++) {
              if (selectedItemKey[j] == datas[i].key) {
                isSelected = true;
                break;
              }
            }
            if (!isSelected) {
              remainArray.push(datas[i]);
            }
          }
          if (remainArray.length > 0) { // 剩余还有数据
            item.datas = remainArray;
          } else { // 剩余没有数据
            if (parentNode == '') {
              store.root = {};
            } else {
              this.deleteParentNode(root, key, parentNode, root);// 所有子项都被选中，则删除item节点本身
            }
          }

          flag = true;
        } else {
          for (let i = 0; i < datas.length; i++) {
            if (this.deleteData(datas[i])) {
              break;
            }
          }
        }
      }
      return flag;
    }

    deleteParentNode=(item, nodeid, parentid, parent) => {
      const { key, isParent, datas } = item;
      let flag = false;
      if (isParent) {
        if (key == parentid) {
          const datasArray = parent.datas;
          for (let i = 0; i < datasArray.length; i++) {
            if (nodeid == datasArray[i].key) {
              datasArray.splice(i, 1);
              flag = true;
              break;
            }
          }
        }
      } else {
        for (let i = 0; i < datas.length; i++) {
          if (this.deleteParentNode(datas[i], key, parentid, item)) {
            break;
          }
        }
      }
      return flag;
    }

    // 拆分条件
    splitCondition=() => {
      const { store } = this.props;
      const { selectedItemKey, root } = store;
      if (selectedItemKey.length > 0) {
        this.splitChangeData(root);
        store.selectedItemKey = [];
        store.selectedItemParentNode = '';
      }
      this.getRuleSql();
      this.changeModified();
    }

    splitChangeData=(item) => {
      const { store } = this.props;
      const { selectedItemKey, selectedItemParentNode } = store;
      const { key, isParent, datas } = item;
      let flag = false;
      if (isParent) {
        if (key == selectedItemParentNode) {
          let newArray = new Array();// 剩余的数据
          for (let i = 0; i < datas.length; i++) {
            let isSelected = false;// 是否被选中
            for (let j = 0; j < selectedItemKey.length; j++) {
              if (selectedItemKey[j] == datas[i].key) {
                isSelected = true;
                break;
              }
            }
            if (!isSelected) {
              newArray.push(datas[i]);
            } else {
              const newDatas = this.getNewDatas(key, datas[i]);
              newArray = newArray.concat(newDatas.slice());
            }
          }
          item.datas = newArray;
          flag = true;
        } else {
          for (let i = 0; i < datas.length; i++) {
            if (this.splitChangeData(datas[i])) {
              break;
            }
          }
        }
      }
      return flag;
    }

    getNewDatas=(pid, item) => {
      const { datas } = item;
      for (let i = 0; i < datas.length; i++) {
        datas[i].parentNode = pid;
      }
      return datas;
    }


    getRelationItems =(itemObj, isRoot) => {
      if (itemObj && itemObj.datas && itemObj.datas.length > 0) {
        const { key, relationship, datas } = itemObj;
        let relationDesc = 'AND';
        if (relationship == '0') {
          relationDesc = 'OR';
        }
        const { store } = this.props;
        let { selectedItemKey } = store;
        let selectedCss = '';
        let title = '';
        title = getLabel(384567, '双击更改关系');
        selectedItemKey = selectedItemKey.slice(0);
        if (!isRoot) {
          if (selectedItemKey.indexOf(itemObj.key) > -1) {
            selectedCss = ' spanselected';
          }
        } else {
          selectedCss = ' isroot';
        }


        return (<div id={`relationblock_${key}`} onClick={(e) => { if (!isRoot) { this.switchSelectedDiv(e, itemObj); } }} className={`relationblock${selectedCss}`} key={key}>
          <div className="verticalblock" title={title} onDoubleClick={() => { this.switchRelationEditMode(itemObj); }}>{relationDesc}</div>
          <div className="relationStyle outermoststyle" >
            <div className="relationStyleTop" />
            <div className="relationStyleCenter" />
            <div className="relationStyleBottom" />
          </div>
          { datas.map((item,index) => {
            const { isParent } = item;
            if (isParent) {
              return <div className="relationItem">{this.getRelationItems(item, false)}</div>;
            }
            const { isEdit } = item;
            if (isEdit && isEdit == 1) {
              return <div id={`relationItemEdit_${key}`}><ConditionEdit ecId={`${this && this.props && this.props.ecId || ''}_ConditionEdit@lsmsce@${index}`} {...this.props} itemdata={item} cancelBackFun={this.cancelBackFun.bind(this)} /></div>;
            }
            return (<span
              className="relationItem"
              id={`relationItem_${key}`}
              onClick={(e) => { if (!isRoot) { this.switchSelectedDiv(e, itemObj); } }}
            >
              {this.expressdescElement(item)}
            </span>);
          })}

        </div>);
      }
      return <div />;
    }

    changeContentHeight=() => {
      const { store } = this.props;
      const dialogHeight = 600;
      let h = dialogHeight - 115;
      const { isShowSql } = store;
      let h1 = 51;
      if ($('.wev-crm-highseas-condition-top').outerHeight() > 51) {
        h1 = $('.wev-crm-highseas-condition-top').outerHeight();
      }
      const h2 = 50;
      let h3 = 0;
      if (isShowSql) {
        h3 = 60;
      }
      h = dialogHeight - h1 - h2 - h3 - 10;
      store.contentHeight = h;
    }


    getRuleSql=() => {
      const { store } = this.props;
      const { isShowSql } = store;
      if (isShowSql) {
        store.getShowSql();
      }
    }


    changeShowSql=() => {
      const { store } = this.props;
      const { isShowSql } = store;
      store.isShowSql = !isShowSql;
      this.changeContentHeight();
      this.getRuleSql();
    }
}
